package com.example.controller.before;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.Address;
import com.example.entity.RelationAddress;
import com.example.service.AddressService;
import com.example.service.RelationAddressService;
import com.example.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

@Api(tags = "用户地址管理")
@CrossOrigin
@RequestMapping("/addressControllerBefore")
@RestController
public class AddressControllerBefore {

    @Autowired
    private AddressService addressService;

    @Autowired
    private RelationAddressService relationAddressService;

    @ApiOperation(value = "添加地址")
    @PostMapping("addAddress/{userId}")
    public R addAddress(
            @ApiParam(name = "address", value = "地址信息", required = true) @RequestBody Address address,
            @ApiParam(name = "userId", value = "用户id", required = true) @PathVariable String userId
    ) {
        boolean b = addressService.addAddress(address, userId);
        if (b) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @ApiOperation(value = "查询地址")
    @GetMapping("listAddress/{userId}")
    public R selectAddress(@PathVariable String userId) {

        //获得关系表里数据
        List<String> listRe = relationAddressService.getList(userId);
        if (listRe.size() > 0) {
            //根据多条id查询地址
            Collection<Address> list = addressService.listByIds(listRe);
            return R.ok().data("address", list);
        }
        return R.ok();

    }

    @ApiOperation(value = "更新地址信息")
    @PostMapping("updateAddress")
    public R updateAddress(
            @ApiParam(name = "address", value = "地址信息", required = true) @RequestBody Address address
    ) {
        boolean b = addressService.updateById(address);
        if (b) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @ApiOperation(value = "删除地址信息")
    @DeleteMapping("deleteAddress/{userId}/{addId}")
    public R deleteAddress(
            @ApiParam(name = "address", value = "地址信息", required = true) @PathVariable String userId,
            @ApiParam(name = "address", value = "地址信息", required = true) @PathVariable String addId
    ) {
        //移除地址
        boolean b = addressService.removeById(addId);
        //移除地址关联表
        QueryWrapper<RelationAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("add_id", addId);
        boolean b1 = relationAddressService.remove(wrapper);
        if (b && b1) {
            return R.ok();
        } else {
            return R.error().message("删除失败！");
        }
    }

}
